package com.college.collegeinfomanage.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UploadController {

    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        if (file.isEmpty()) {
            response.put("code", 400);
            response.put("message", "文件为空");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            // 获取文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            // 获取 resources 目录路径
            String resourcePath = new ClassPathResource("static/images").getFile().getAbsolutePath();
            File saveFile = new File(resourcePath, fileName);

            // 确保目录存在
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }

            // 保存文件
            file.transferTo(saveFile);

            // 动态获取服务器地址
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();

            // 返回完整的文件访问URL
            String fileUrl = serverUrl + "/images/" + fileName;
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", fileUrl);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            e.printStackTrace();
            response.put("code", 500);
            response.put("message", "文件上传失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
